<?php
/**
 * 
 * @author spring
 * @version 2014-6-7 上午8:57:50
 */
class  Controller_Delivery extends Controller_Admin {
	
/**
 *手动新建出库单
 *
 */
    public function before()
    {
    	try {
    		  ACL::Required('delivery');
    	} catch ( HTTP_Exception_403 $e ) {
				Message::error('sorry，你没有权限进这个目录');
    		$this->request->redirect ( URL::base (true) );
    	}
        parent::before();
    }
	/**
	 * 
	 * Description 这个暂时没用
	 * 
	 */
	public function action_index()
 	{
 		$this->title='扫描出库';
 	    set_time_limit(0);
	    ini_set('memory_limit','500M');
	    $start='';
	    $end='';
		 if(!isset($_GET['start'])||!isset($_GET['end'])){
		 	$start=$end=date('Y-m-d H:00:00',strtotime("-1 hour "));
		 	$end=date('Y-m-d H:00:00');
		  }else {
		  	$start=$_GET['start'];
		  	$end=$_GET['end'];
			  }
			  $start='2014-07-01 13:50:00';
			  $end='2014-07-01 13:59:00';
		  $i=0;
		  $defaultrate=DB::select('rate1')->from('rates')->where('name','=','$')->execute('newerp')->get('rate1');
		  $orders=DB::select('oldid','erp_orders_id','currency_type','orders_out_time','sales_account','orders_export_time')->from('erp_orders')->where('orders_out_time','>=',$start)->and_where('orders_out_time','<',$end)->and_where('orders_status','=',5)
		  ->execute('readonlyerp')->as_array();
		  foreach ($orders as  $order){
		  	if(!$order['currency_type']){
		  		$order['currency_type']=DB::select('currency_type')->from('erp_orders')->where('erp_orders_id','=',$order['oldid'])->execute('readonlyerp')->get('currency_type',0);
		  	}
		  	$rss=DB::select('orders_products_id','orders_sku','item_price','item_count')->from('erp_orders_products')->where('erp_orders_id','=',$order['erp_orders_id'])->execute('readonlyerp')->as_array();
		  	foreach ($rss as $rs){
		  		if(count($rs)){
		  			$i++;
		  			$skuinfo=Basic::load_sku_info($rs['orders_sku']);
		  			$condition['delivery_date']=$order['orders_out_time'];
		  			$condition['order_id']=$order['erp_orders_id'];
		  			$condition['orders_products_id']=$rs['orders_products_id'];
		  			$condition['sku']=$rs['orders_sku'];
		  			$condition['sku_name']=$skuinfo['products_name_cn'];
		  			$condition['sku_standard']=$skuinfo['size'];
		  			$condition['storage_position']=$skuinfo['products_place'];
		  			$condition['quantity']=$rs['item_count'];
		  			$condition['remark']='正常出库';
		  			$condition['type']=10;
		  			if($rs['item_price']==0){
		  				echo '订单号为'.$order['erp_orders_id'].'订单物品单价为0 请手动在入库单添加单价并计算成本（成本=单价*数量）[1]\n';
		  			}
		  			$rate= DB::select('rate1')->from('rates')->where('name','=',$order['currency_type'])->and_where('rate_time','<=',$order['orders_out_time'])->order_by('rate_time','desc' )->limit(1)->offset(0)->execute('newerp')->get('rate1',$defaultrate);
		  			$condition['single_price']=$rs['item_price']*$rate;
		  			echo $rate.'-'.$order['currency_type'].'-'.$order['orders_export_time'].'-'.$condition['orders_products_id'].'<br>';
		  			$flag=DB::select('order_id')->from('deliveryorders')->where('orders_products_id','=',$rs['orders_products_id'])->execute('newerp')->get('order_id',0);
		  			if(!$flag){
		  				if(!Delivery::insert_delivery1($condition)){
		  					echo '订单号为'.$order['erp_orders_id'].'入新系统失败[2]\n';
		  				}
		  			}else {
		  				echo '订单号为'.$order['erp_orders_id'].'重复入新系统失败[3]\n';
		  			}
		  		}else {
		  			echo '订单号为'.$order['erp_orders_id'].'没有订单物品[4]\n';
		  		}
		  	}
		  }
	    echo '执行条数：'.$i;
 		$content=View::factory("delivery/index");
 		$this->response->body($content);
 	}
 	
	/**
	 * 
	 * Description   创建出库单，目的是为了非扫描出库来做的，如果库存不足将不能出库
	 * 
	 */
	public function  action_special()
	{
		$this->title='新建出库单';

		if(Delivery::is_post()){

            /**
             * BUG问题，计算库存问题
             */
//            $tablename='inventories';
//			//下面三行代码是查看sku库存量，调用的是盘点的方法。
//			$pre= Pandian::getListInfoCondition(Pandian::getListPre($tablename),array('sku'=>$_POST['sku'],'start_time'=>date('Y-m-d')),true,$tablename);
//			$datas=Pandian::getList(1,0,$pre);
//			$datas=Pandian::excute_data($datas,date('Y-m-d H:i:s'));
//			$quantity=isset($datas[0]['quantity'])?$datas[0]['quantity']:0;

            /**
             * @author zhjx
             * @time 20141030
             * 计算当前的库存信息
             */
            $sy = 0;
            if(true) {
                $sku = strtoupper(trim($_POST['sku']));
                $warehouseid = $_POST['warehouseid'];

                if (!$warehouseid) {
                    $jsonarr = array('status' => 'n','info' => '请选择仓库!');
                    echo json_encode($jsonarr);
                    exit;
                }

                $enterprise_dominant = $_POST['enterprise_dominant'];
                //$inventory = Warningtmp::get_inventory_for_vmi(array($sku), $warehouseid, $enterprise_dominant);
                $enterprise_dominant = !empty($enterprise_dominant)?$enterprise_dominant:0;
                $inventory = Inventory::get_sku_real_stocks(array($sku), array('warehouse_id'=>$warehouseid,'enterprise_dominant'=>$enterprise_dominant));
                $quantity = isset($inventory[$sku]) ? $inventory[$sku] : 0;
                $sy = $quantity - $_POST['quantity'];
            }

            $_POST['delivery_date'] = date('Y-m-d H:i:s');
			if(Basic::checktime($_POST['delivery_date'])){
				$jsonarr = array('status'=>'n','info'=>'关账期间不能新建出库，请找财务');
				echo json_encode($jsonarr);
				exit();
			}


			if($sy >= 0) {
				$condition = $_POST;
				if($id = Delivery::insert_delivery($condition)){
					Basic::log(array('sku' =>$condition['sku'],'value'=>'特殊出库一条记录','type'=>Basic::INSERT,'controller'=>$this->request->controller(),'action'=>$this->request->action(),'table_name'=>'deliveryorders','table_id'=>$id));
					$jsonarr=array('status'=>'y','info'=>'提交成功','id'=>$id);
				}else {
					$jsonarr=array('status'=>'n','info'=>'提交失败');
				}
			}else {
				$jsonarr=array('status'=>'n','info'=>'库存不足，目前只有'.$quantity.'个');
			}
			echo json_encode($jsonarr);
			exit();
		}else {
		    $status=Delivery::get_delivery_status('deliveryorders','type');
            $warehouse = Kohana::$config->load('warehouse')->warehouses;
            //$warehouse   = delivery::get_warehouse_list();
            $enterprise_dominants = Kohana::$config->load('enterprise_dominant')->as_array();
		    //部门暂时还没用，仅仅数组代替
			$content=View::factory("delivery/special")->set('warehouse', $warehouse)
			    ->set('status',$status)->set('enterprise_dominants', $enterprise_dominants);
			$this->response->body($content);
		}
	}
	/**
	 * 
	 * Description
	 *下载上传出库单的表格
	 */
	public function action_down_template()
	{
		$this->title='下载模版';
		require_once(Kohana::find_file('vendor', 'PHPExcel/PHPExcel/IOFactory'));
		$this->objReader  = PHPExcel_IOFactory::createReader('Excel5');
		$objPHPExcel      = new PHPExcel();
		$objPHPExcel->getProperties()->setCreator("yksvmi")
		->setLastModifiedBy("newerp")
		->setTitle("Office 2003 XLSX Test Document")
		->setSubject("Office 2003 XLSX Test Document")
		->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
		->setKeywords("office 2003 openxml php")
		->setCategory("Test result file");
		$objActSheet =$objPHPExcel->setActiveSheetIndex(0);
		$objActSheet->setCellValue('A1', '出库类型');
		$objActSheet->setCellValue('B1', 'SKU');
		$objActSheet->setCellValue('C1', '数量');
		$objActSheet->setCellValue('D1', '出库时间');
		$objActSheet->setCellValue('E1', '备注');
        $objActSheet->setCellValue('F1', '仓库ID');
		$objPHPExcel->getActiveSheet()->setTitle('delivery_special');
		$objPHPExcel->setActiveSheetIndex(0);
		$day=date("m-d");
        ob_end_clean();
		header("Content-Type: application/vnd.ms-excel; charset=utf-8");
		header('Content-Disposition: attachment;filename="'.$day.'出库单.xls"');
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		exit;
	}
	
	/**
	 *
	 * Description
	 * 执行上传出库单的操作
	 */
	public function  action_upload_delivery()
	{
	 	$view=View::factory("delivery/special_upload_result");
		$this->title='出库批量上传结果';
		set_time_limit(0);
	 	ini_set('memory_limit','500M');
	 	require_once(Kohana::find_file('vendor', 'PHPExcel/PHPExcel/IOFactory'));
	 	$xls= $_FILES['xls']['tmp_name'];
	 	$objPHPExcel= PHPExcel_IOFactory::load($xls);
	 	$data= $objPHPExcel->getActiveSheet()->toArray(null,true,true,true,true,true);
	 	$result=Delivery::check_special_upload($data);
	 	if($result['flag']==0){
		 	$lines=Delivery::do_special_upload($data);
		 	$view->lines=$lines;
	 	    $view->message='数据全部上传成功';
	 	}else{
	 		$view->message='提交成功0行,有'.$result['flag'].'条记录有误,请更改后重新上传:';
			$view->result=$result;		 		
	 	}
		$this->response->body($view);
	}
	
	
}
